package com.forgenet.testclient.panel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class GamePanel extends JPanel implements ActionListener {

    private static final int CELL_SIZE = 50;
    private static final int ROWS = 12;
    private static final int COLS = 12;
    private static final int MAP_WIDTH = CELL_SIZE * ROWS;
    private static final int MAP_HEIGHT = CELL_SIZE * COLS;
    private static final int PLAYER_WIDTH = 50;
    private static final int PLAYER_HEIGHT = 50;

    private int playerX;
    private int playerY;

    private final Timer timer;

    public GamePanel() {
        setPreferredSize(new Dimension(MAP_WIDTH, MAP_HEIGHT));
        setFocusable(true);

        addKeyListener(new PlayerMovementListener());

        playerX = 0;
        playerY = 0;


        timer = new Timer(10, this);
        timer.start();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        repaint();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        // 绘制地图
        g.setColor(Color.BLACK);

        for (int row = 0; row < ROWS; row++) {
            for (int col = 0; col < COLS; col++) {
                int x = col * CELL_SIZE;
                int y = row * CELL_SIZE;
                g.drawRect(x, y, CELL_SIZE, CELL_SIZE);
            }
        }

        g.setColor(Color.RED);
        g.fillRect(playerX, playerY, PLAYER_WIDTH, PLAYER_HEIGHT);
    }

    private class PlayerMovementListener extends KeyAdapter {
        @Override
        public void keyPressed(KeyEvent e) {
            switch (e.getKeyCode()) {
                case KeyEvent.VK_UP:
                    playerY -= CELL_SIZE;
                    break;
                case KeyEvent.VK_DOWN:
                    playerY += CELL_SIZE;
                    break;
                case KeyEvent.VK_LEFT:
                    playerX -= CELL_SIZE;
                    break;
                case KeyEvent.VK_RIGHT:
                    playerX += CELL_SIZE;
                    break;
            }

            playerX = Math.max(playerX, 0);
            playerY = Math.max(playerY, 0);
            playerX = Math.min(playerX, MAP_WIDTH - PLAYER_WIDTH);
            playerY = Math.min(playerY, MAP_HEIGHT - PLAYER_HEIGHT);
        }
    }


    private static boolean loginUser(String username, String password) {
        // 这里可以添加登录逻辑，比如检查数据库中是否存在该用户并且密码正确
        // 如果登录成功，返回 true，否则返回 false
        return true;
    }

    private static boolean createUser(String username, String password) {
        // 这里可以添加创建用户逻辑，比如将用户名和密码写入数据库
        // 如果创建成功，返回 true，否则返回 false
        return true;
    }

}
